// pages/to-pay-order/to-pay-order.js
const apiurl = require('../../config').apiurl;
import {
  Pulibc
} from '../../models/public.js'
const pulibc = new Pulibc()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods_freight: null,
    goodsList: [],
    addressInfo: null,
    selectShow: false,
    amount: 0,
    address_id: 0,
    unconsumed: 0,
    remarks: '',
    is_balance: '',
    select_id: false,
    member_gradeid: 0 // member_gradeid 0 非会员 1会员，2代理，3经销商，4众筹，5众筹+股份
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    this.getMemberInfo();
    // 切换地址时缓存ids
    if (options.ids || options.id) {
      let ids = options.ids || options.id;
      wx.setStorageSync('ids', ids);
      wx.setStorageSync('ifcart', options.ifcart);
      this.getPayDetail(ids);
    }
    if (options.address_id) {
      let address_id = options.address_id;
      let ids = wx.getStorageSync('ids');
      this.getPayDetail(ids, address_id);
      this.setData({
        address_id
      })
    }
  },
  // 隐藏选择支付
  hideSelect() {
    this.setData({
      selectShow: false
    })
  },
  // 获取会员接口
  getMemberInfo() {
    var keyVal = wx.getStorageSync('key');
    console.log(keyVal)
    wx.request({
      url: apiurl + '/member/index',
      data: {
        key: keyVal
      },
      success: data => {
        console.log(data.data.datas.member_info)
        if (data.data.code == 200) {
          var member_gradeid = data.data.datas.member_info.member_gradeid;
          let unconsumed = data.data.datas.member_info.unconsumed
          // member_gradeid 0 非会员 1会员，2代理，3经销商，4众筹，5众筹+股份
          this.setData({
            member_gradeid,
            unconsumed
          })
        }
      }
    })
  },
  // 显示选择支付
  orderSelect() {
    let is_balance = this.data.is_balance
    console.log(is_balance)
    if (is_balance == 1) {
      this.createOrder();
      return;
    }
    this.setData({
      selectShow: true
    })
  },
  // 是否使用余额支付
  changeIsSwith(e) {
    // console.log()
    let select_id = e.detail.value
    this.setData({
      select_id
    })
  },
  // 使用余额支付
  createOrder111() {
    // 清除购物车缓存
    wx.removeStorageSync('cartList');
    if (!this.data.addressInfo) {
      pulibc.showToast('请先添加收货地址哦~', 'none');
      return;
    }
    let address_id = this.data.address_id;
    let url = apiurl + '/memberbay/buy_step2';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.cart_id = wx.getStorageSync('ids');
    params.remarks = this.data.remarks;
    params.ifcart = wx.getStorageSync('ifcart');
    if (wx.getStorageSync('ifcart')) {
      params.ifcart = wx.getStorageSync('ifcart');
    } else {
      params.ifcart = '';
    }
    // 判断用户是否切换地区
    if (this.data.address_id) {
      params.address_id = this.data.address_id;
    } else {

      params.address_id = this.data.addressInfo.address_id;
    }

    // 获取是否使用余额
    let select_id = this.data.select_id
    console.log(select_id)

    // 如果当期余额>=总金额就使用余额支付
    if (this.data.unconsumed >= this.data.amount && this.data.select_id) {
      this.getBalance(url, params)
      return;
    }


    this.getOrderData(url, params)
  },
  // 封装微信支付
  getOrderData(url, params) {
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: res => {
        console.log(res)

        if (res.data.code == 200) {
          // 调用微信支付接口
          let pay_sn = res.data.datas.pay_sn;
          let url = apiurl + '/memberpayment/pay_new';
          let params = {};
          params.key = wx.getStorageSync('key');
          params.pay_sn = pay_sn;
          wx.request({
            url: url,
            data: params,
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            method: 'POST',
            success: res => {
              console.log(res)
              if (res.data.code == 200) {
                // 发起微信支付
                wx.requestPayment({
                  timeStamp: res.data.datas.wx.timeStamp,
                  nonceStr: res.data.datas.wx.nonceStr,
                  package: res.data.datas.wx.package,
                  signType: res.data.datas.wx.signType,
                  paySign: res.data.datas.wx.paySign,
                  appId: res.data.datas.wx.appId,
                  fail: function(error) {
                    console.log(JSON.stringify(error))
                    wx.showToast({
                      title: '支付失败:'
                    })
                    wx.switchTab({
                      url: '/pages/user/user'
                    });
                  },
                  success: function() {
                    wx.showToast({
                      title: '支付成功'
                    })
                    wx.switchTab({
                      url: '/pages/user/user'
                    });
                  }
                })
              } else {

              }

            }
          })
        } else if (res.data.datas.error == '请登录') {
          wx.navigateTo({
            url: "../register/register"
          })
        }
      }
    })
  },
  // 生成订单
  getGenerateOrder(url, params) {
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: res => {
        console.log(res)

        if (res.data.code == 200) {
          wx.switchTab({
            url: "/pages/user/user"
          })
        }
      }
    })
  },
  // 使用余额支付(不调用微信支付)
  getBalance(url, params) {
    // let url = apiurl + '/memberbay/buy_step2';
    wx.showModal({
      title: "是否使用余额支付",
      success: res => {
        if (res.confirm){ // 确定才调起
          this.getGenerateOrder(url, params);
        }else{ // 取消

        }
        
      },
      fail:error=>{
        console.log(error)
      },
     
    })
  },
  // 提交订单
  createOrder() {
    // 清除购物车缓存
    wx.removeStorageSync('cartList');
    if (!this.data.addressInfo) {
      pulibc.showToast('请先添加收货地址哦~', 'none');
      return;
    }
    let address_id = this.data.address_id;
    let url = apiurl + '/memberbay/buy_step2';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.cart_id = wx.getStorageSync('ids');
    params.remarks = this.data.remarks;
    params.ifcart = wx.getStorageSync('ifcart');
    if (wx.getStorageSync('ifcart')) {
      params.ifcart = wx.getStorageSync('ifcart');
    } else {
      params.ifcart = '';
    }
    // 判断用户是否切换地区
    if (this.data.address_id) {
      params.address_id = this.data.address_id;
    } else {

      params.address_id = this.data.addressInfo.address_id;
    }
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: res => {
        console.log(res)

        if (res.data.code == 200) {
          // 调用微信支付接口
          let pay_sn = res.data.datas.pay_sn;
          let url = apiurl + '/memberpayment/pay_new';
          let params = {};
          params.key = wx.getStorageSync('key');
          params.pay_sn = pay_sn;
          wx.request({
            url: url,
            data: params,
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            method: 'POST',
            success: res => {
              console.log(res)
              if (res.data.code == 200) {
                // 发起微信支付
                wx.requestPayment({
                  timeStamp: res.data.datas.wx.timeStamp,
                  nonceStr: res.data.datas.wx.nonceStr,
                  package: res.data.datas.wx.package,
                  signType: res.data.datas.wx.signType,
                  paySign: res.data.datas.wx.paySign,
                  appId: res.data.datas.wx.appId,
                  fail: function(error) {
                    console.log(JSON.stringify(error))
                    wx.showToast({
                      title: '支付失败:'
                    })
                    wx.switchTab({
                      url: '/pages/user/user'
                    });
                  },
                  success: function() {
                    wx.showToast({
                      title: '支付成功'
                    })
                    wx.switchTab({
                      url: '/pages/user/user'
                    });
                  }
                })
              } else {

              }

            }
          })
        } else if (res.data.datas.error == '请登录') {
          wx.navigateTo({
            url: "../register/register"
          })
        }
      }
    })

  },
  bindRemarks(e) {
    let remarks = e.detail.value;
    // console.log(remarks)
    this.setData({
      remarks
    })
  },
  // 切换地址
  selectAddress() {
    wx.reLaunch({
      url: '../address/address?changeBool=1',
    })
    // pulibc.navigateUrl('../address/address?changeBool=1');
  },
  // 待付款订单详情
  getPayDetail(ids, address_id) {
    let url = apiurl + '/memberbay/buy';
    let params = {};
    params.key = wx.getStorageSync('key');
    params.cart_id = ids;
    if (wx.getStorageSync('ifcart')) {
      params.ifcart = wx.getStorageSync('ifcart');
    } else {
      params.ifcart = '';
    }
    // 判断用户是否切换地址
    if (address_id) {
      params.address_id = address_id;
    }
    wx.request({
      url: url,
      data: params,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: res => {
        console.log(res)
        let goodsList = res.data.datas.goods_list;
        let addressInfo = res.data.datas.address_info;
        let amount = 0;
        let is_balance = res.data.datas.is_balance
        // let amount = res.data.datas.order_amount;
        let goods_freight = res.data.datas.goods_freight;
        goodsList.map(item => {
          if (this.data.member_gradeid == 0) {
            item.goods_price = item.goods_price;
          } else if (this.data.member_gradeid == 1) {
            item.goods_price = item.retail_price;
          } else {
            item.goods_price = item.wholesale_price;
          }
          amount += parseFloat(item.goods_price) * item.goods_num;
        })
        amount += parseFloat(goods_freight);
        this.setData({
          goodsList,
          addressInfo,
          amount,
          goods_freight,
          is_balance
        })
      }
    })
  },
  addAddress(e) {
    wx.reLaunch({
      url: '/pages/address-add/address-add?changeBool=1',
    })
    // pulibc.navigateUrl('/pages/address-add/address-add?changeBool=1');
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (wx.getStorageSync("key") == false) {
      wx.navigateTo({
        url: "../register/register"
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})